$(function () {
	//绑定 按钮事件
	$('#button2').on('click',sysUserJs.addUser);
	$('#button1').on('click',sysUserJs.deleteUsers);
	$('#btn-simple-search').on('click',sysUserJs.fuzzyQuery);
	//表格初始化
	sysUserJs.initUserTable();
	$('#grantRoles').select2();
	$('#w_roleList').select2();
	$("#w_authtreeScroll").mCustomScrollbar();
	$("#w_areaTreeScroll").mCustomScrollbar();
	sysUserJs.initWizardModal();
	sysUserJs.initAuthTree();
	
	var statusChangeCall =  function ( $realCheckBox , isSelect ){
		   var tr = $realCheckBox.parent().parent();
//		   if( isSelect ){
//			   //移除所有选中
//			   var tbody = tr.parent();
//			   var allTrs = tbody.children();
//			   allTrs.removeClass("nmsTrSelect");
//			   tbody.find("input[type='checkbox']").prop("checked" , false);
//		   }
		   if( isSelect ){
			   $realCheckBox.prop("checked" , true);
			   tr.addClass("nmsTrSelect");
		   }else{
			   $realCheckBox.prop("checked" , false);
			   tr.removeClass("nmsTrSelect");
		   }
	   }
	   nmsckb.preBindClickEvent(statusChangeCall);
});
 

var sysUserJs = {};
sysUserJs.userid = null;

/*常量*/
var CONSTANT = {
        DATA_TABLES : {
            DEFAULT_OPTION : { //DataTables初始化选项
                language: {
                    "sProcessing":   sysi18n.processing_,
                   	"sLengthMenu":   sysi18n.length_menu,
                    "sZeroRecords":  sysi18n.no_matching_result,
					"sInfo":         sysi18n.DT_Info, 
                    "sInfoEmpty":    sysi18n.DT_Info_Empty,
          //          "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
                    "sInfoPostFix":  "",
                    "sSearch":       sysi18n.search_,
                    "sUrl":          "",
                    "sEmptyTable":     sysi18n["the data in the table is empty"],
                    "sLoadingRecords": sysi18n.loading_,
                    "sInfoThousands":  ",",
                    "oPaginate": {
                        "sFirst":    sysi18n["first page"],
                        "sPrevious": sysi18n["previous page"],
                        "sNext":     sysi18n["next page"],
                        "sLast":     sysi18n["last page"],
                        "sJump":     sysi18n["jump pages"]
                    },
                    "oAria": {
                        "sSortAscending":  sysi18n.ascending_order,
                        "sSortDescending": sysi18n.descending_order
                    }
                },
                autoWidth: true,   //禁用自动调整列宽
                stripeClasses: ["odd", "even"],//为奇偶行加上样式，兼容不支持CSS伪类的场合
//                order: [],          //取消默认排序查询,否则复选框一列会出现小箭头
                processing: false,  //隐藏加载提示,自行处理
                serverSide: true,   //启用服务器端分页
                searching: false    //禁用原生搜索
            },
            COLUMN: {
                CHECKBOX: { //复选框单元格.
                  	className: "td-checkbox",
                    orderable: false,
                    width: "30px",
                    data: null,
                    render: function (data, type, row, meta) {
                        return '<input type="checkbox" class="nmsckb nmsCheckboxS" name="checkList" data-user-id="'+data.userId+'" ><label class="nmsckbLabel" ></label>';
                    }
                }
            },
            RENDER: {   //常用render可以抽取出来，如日期时间、头像等
                ELLIPSIS: function (data, type, row, meta) {
                    data = data||"";
                    return '<span title="' + data + '">' + data + '</span>';
                }
            }
        }
};

sysUserJs.initUserTable = function (){
		sysUserJs.table = $('#userlist').DataTable({
		"dom":'<"top"l>rt<"bottom"ip><"clear">',
		"lengthChange": true,//是否允许用户自定义显示数量
		"lengthMenu": [
            [10, 20, 50],
            [10, 20, 50]
        ],//每页显示条数设置
		"sPaginationType": "full_numbers",
        "iDisplayLength": 10,
        "bAutoWidth": false, 
 //       "bLengthChange":false,
//        "oLanguage":CONSTANT.DATA_TABLES.DEFAULT_OPTION.language,
        language : commonI18n.tableI18n,
        "bProcessing": true, 
        "bServerSide": true, 
        'bStateSave': true,
        "fnServerParams" : function(aoData) {  
            aoData.push({  
                "name" : "searchText",  
                "value" : encodeURI($("#fuzzy-search").val())  
            });  
        },
        "sAjaxSource": "sys/QueryUser", //给服务器发请求的url
        columns :[
            {"mData": null, "targets": 0},
            //复选框
             CONSTANT.DATA_TABLES.COLUMN.CHECKBOX,
            {"mData": 'username'},
            {"mData": 'phone'},
            {"mData": 'email'},
//            {"mData": 'createTimestamp'},
//            {"mData": 'lastUpdateTimestamp'},
            {"mData": 'userRemark'},

           // {"mData": 'sysUserStatus'},
            {"mData": null, 
             render: function (data, type, row, meta) {
                        if(data.sysUserStatus==1){
							return sysi18n.normal;
						}else{
							return sysi18n.frozen;
						}
                     }
            },
//            {"mData": 'lastLoginTime'},
//            {"mData": 'loginNum'},
            {className : "td-operation",
             data:null ,
             defaultContent:"",
             orderable : false,
             width : "120px"
            },
        ],
        
        "createdRow": function ( row, data, index ) {
        	var $btnEdit = $('<h4 style="display: inline"><a onclick="sysUserJs.editUser(this)"><i class="glyphicon glyphicon-edit "></i></a></h4>');
            var $btnDel = $('<h4 style="display: inline"><a onclick="sysUserJs.deleteSingleUser(this)"><i class="glyphicon glyphicon-remove"></i></a></h4>');
            $('td', row).eq(7).append($btnEdit).append($btnDel);
        },
        
        "fnDrawCallback" :function(){
        	var api = this.api();
        	//给行加序号
        	api.column(0).nodes().each(function(cell, i) {
        		cell.innerHTML =  api.context[0]._iDisplayStart + i +1;
        	}); 
        }
    });

		//checkbox全选
		$("#checkAll").on("click", function () {
			if ($(this).prop("checked") == true) {
				$("input[name='checkList']").prop("checked", $(this).prop("checked"));
				$("input[name='checkList']").parents("tr").addClass("nmsTrSelect");
			} else {
				$("input[name='checkList']").prop("checked", false);
				$("input[name='checkList']").parents("tr").removeClass("nmsTrSelect");
			}
		});

}

//sysUserJs.addUser = function(){
//	$("#adduser").show();
//	sysUserJs.addUserPage = layer.open({
//				  type: 1,
//				  title:sysi18n["Add sysUser"],
//				  area: ['400px', '200px'],
//				  shadeClose: true, //点击遮罩关闭
//				  content: $('#adduser')
//				  });
//
//}


sysUserJs.deleteUsers = function(){
	sysShowConfirm(function(){
		var userValue = [];
		var usernames = [];
		$("input[name='checkList']").each(function() {
	    	if ($(this).prop("checked") == true) {
	    		userValue.push($(this).attr("data-user-id"));
	    		usernames.push($($(this).parents('tr').children().eq(2)).text());
	        }
	    });
		if (userValue.length==0) {
			layer.alert(sysi18n["Please select an option at least"],{title:""});
			return false;
	    }else {
	    	   var url = 'sys/DeleteUserByID';
	    	   var data = { 
	    			   "userID[]" : userValue,
	    			   "usernames[]":usernames,
	    	   };   
	    	   var successCallBack = function(data) {
	    		   if( data.results ){
	                   sysShowSuccessTip( sysi18n.delete_success );
	                   $("#userlist").dataTable().fnPageChange( 'previous', true ); 
	    		   }else{
	    			   sysShowTip(sysi18n.delete_fail);
	    			}
		       }   
		    	   $.sysAjax(  url , data , successCallBack );  
		       }
		},function(){
			parent.layer.closeAll();
			return false;
		},sysi18n.remove_confirm);

}

sysUserJs.createUser = function(){
	var password=$("#w_passward").val();
	var username=$("#w_username").val();
	var phone = $("#w_phone").val();
	var email = $("#w_email").val();
	if(username!=""&&password!=""){
		var url = "sys/addSysUser";
		var uroles = $("#w_roleList").val();
		var data = {
			uname : username,
			upass : password,
			phone : phone,
			email : email,
			"roles[]":uroles,
		};
		
		var successCallBack = function(data){
			if( data.result ){
				$("#userlist").dataTable().fnPageChange( 'previous', true ); 
				sysUserJs.wizardModal.submitSuccess();
				sysUserJs.wizardModal.hideButtons();
				sysUserJs.wizardModal.updateProgressBar(0);
			}else{
				sysUserJs.wizardModal.submitFailure();
				sysUserJs.wizardModal.hideButtons();
				sysUserJs.wizardModal.updateProgressBar(0);
			}
		};
		
		$.sysAjax( url , data , successCallBack );
	}else{
		sysShowTip(sysi18n["Account or password can not be empty"]);
	}

}

sysUserJs.fuzzyQuery =function(){
	sysUserJs.table.ajax.reload();
};	


sysUserJs.deleteSingleUser = function(e){
	sysShowConfirm(function(){
		var userid = $($(e).parents('tr').children().eq(1)).find("input").attr("data-user-id");
		var url = 'sys/DeleteUserByID';
		var data = { "userID[]" : userid};
		var successCallBack = function(data) {
			if( data.results ){
		           sysShowSuccessTip( sysi18n.delete_success );
		           $("#userlist").dataTable().fnPageChange( 'previous', true ); 
			}else{
				sysShowTip( sysi18n.delete_fail );
			}
	    }
		
		$.sysAjax( url , data , successCallBack );
	},function(){
		parent.layer.closeAll();
		return false;
	},sysi18n.remove_confirm);
	
}


sysUserJs.editUser = function(e){
	$("#editUserInfoForm")[0].reset();
	sysUserJs.userid = $($(e).parents('tr').children().eq(1)).find("input").attr("data-user-id");
	sysUserJs.username=$($(e).parents('tr').children().eq(2)).text();
	
	var url = "sys/findAllRoles_userRole";
	var data = {
			uid:sysUserJs.userid
			};
	
	var successCallBack = function(data) {
		
		var results = data.result;//所有角色
		
		var result2 = data.result2;//该用户所拥有的角色
		var roleIds = [];
		for(var index in result2){
			roleIds.push( result2[index].roleId );
		}
		
		var roleSelect = $("#grantRoles");
		var options = "";
		for( var index in results ){
			var flag = 0;
			for(var n=0;n<roleIds.length;n++){
				if(results[index].roleId==roleIds[n]){
					options += "<option value='"+results[index].roleId+"' selected='selected' >"+results[index].roleName+"</option>";
					flag = 1;
				}
			}
			if(flag == 0){
				options += "<option value='"+results[index].roleId+"'>"+results[index].roleName+"</option>";
			}
			
		}
		roleSelect.html(options );
		
		var user = data.userInfo;
		$("#username_").val(user.username);
		
		$("#createTime").val(user.createTimestamp);
		$("input[type='radio'][name='userStatus'][value='" + user.sysUserStatus + "']").prop("checked", "checked");
		$("#lastUpdateTime").val(user.lastUpdateTimestamp);
		$("#userPhone").val(user.phone);
		$("#lastLoginTime").val(user.lastLoginTime);
		$("#userEmail").val(user.email);
		$("#loginCounter").val(user.loginNum);
		$("#userRemark").val(user.userRemark);
		
		
		sysUserJs.editPage = layer.open({
			type: 1,
			title:sysi18n["edit user information"],
			area: ['800px', '400px'],
			shadeClose: true, //点击遮罩关闭
			content: $('#editUserInfo'),
			zIndex : 2,
			shade: 0
		});
		$("#grantRoles").parent().children(".select2-container").css("width","200px");
	};
	$.sysAjax(url, data, successCallBack);
	
	


}

sysUserJs.saveUserChange = function() {
	// function saveUserChange(){
	
	var status = null;
	var upass = $("#password").val().trim();
	if(upass.length > 0){
		if(upass.length < 6){
			sysShowErrorTip(commonI18n.PasswordLengthLimit);
			return;
		}
		if(upass != $("#password2").val().trim()){
			sysShowErrorTip(sysi18n.Password_input_is_different);
			return;
		}
	}
//	if (upass.length >= 6) {// 密码不少于6位
//		if (upass.indexOf("a") != -1) {// 密码包含指定字符
	sysShowGlobalLoading();
	var url = "sys/updataUser";
	if ($('#userStatus1').prop("checked")) {
		status = $("#userStatus1").val()
	} else {
		status = $("#userStatus2").val()
	}
	var uroles = $("#grantRoles").val();
	var data = {
			upass : upass,
			uStatus : status,
			uRemark : $("#userRemark").val(),
			uPhone : $("#userPhone").val(),
			uEmail : $("#userEmail").val(),
			uid : sysUserJs.userid,
			roles : uroles,
			username : sysUserJs.username
	};

	var successCallBack = function(data) {
		if (data.results) {
			sysShowSuccessTip(sysi18n.revamp_success);
			$("#userlist").dataTable().fnPageChange('previous', true);
			parent.layer.close(sysUserJs.editPage);
		} else {
			sysShowTip(sysi18n.revamp_fail);
			parent.layer.close(sysUserJs.editPage);
		}
	};

	$.sysAjax(url, data, successCallBack);
//		} else
//			sysShowErrorTip(commonI18n.PasswordContainCharacter);
//	} else
//		sysShowErrorTip(commonI18n.PasswordLengthLimit);

}
sysUserJs.initWizardModal=function(){
	sysUserJs.wizardModal = $("#createUserWizard").wizard( { 
	    	keyboard : false,
			contentHeight : 500,
			contentWidth : 900,
			backdrop: 'static' , 
			buttons:{
				cancelText: commonI18n.Cancel ,
				nextText: commonI18n.Next,
				backText: commonI18n.Back,
				submitText: sysi18n.Create ,
				submittingText: sysi18n.Create_ ,
			}
			
	    }) ;
	    
	    // decrementCard 上一页
	sysUserJs.wizardModal.on( "incrementCard", function (){
//			sysUserJs.roleCheckBox();
//			$("#w_edit").removeAttr("disabled");
//			$("#w_finish").attr("disabled","disabled");
////			 $('input:belongList').click(function () { 
////					sysUserJs.showAreaByRole();
////				  });   
//			sysUserJs.initAreaTree();
		
	    }).on( "submit" , function(){
	    	
	    	sysUserJs.createUser();
	    });
	    
	sysUserJs.wizardModal.cards["card1"].on("validate", function(card) {
		var uroles = $("#w_roleList").val();
		var uname = $("#w_username").val();
		var	upass = $("#w_passward").val();
		var	upassagain = $("#w_passwardAgain").val();
	    	if( uroles == null || uroles.length == 0 ||uname==null||uname.length==0||upass==null||upass.length==0||upassagain.length==0||upassagain==null){
	    		
	    		sysShowErrorTip(sysi18n.CheckInput);
	    		return false;
	    	}
	    	else
	    	{
	    		if(upass!=upassagain){
	    			sysShowErrorTip(sysi18n.PasswordDifferent);
	    			return false;
	    		}
	    		else{
	    			if(upass.length<6){
	    				sysShowErrorTip(sysi18n.PasswordLengthLimit);
		    			return false;
	    			}
//	    			else{
//	    				if(upass.indexOf("a")==-1){
//	    					sysShowErrorTip(sysi18n.PasswordContainCharacter);
//			    			return false;
//	    				}
	    				else
	    					return true;
//	    			}
	    		   
	    		}
	    	}
	    	
	     
	    });
	    
	    $(".w_closeModal").click(function() {
	    	sysUserJs.wizardModal.hide();
	    	sysUserJs.udWizardReset();
		});
	    
	    $(".w_createNewUser").click(function() {
	    	sysUserJs.udWizardReset();
		});
	    $(".w_createNewUser2").click(function() {
	    	sysUserJs.wizardModal.reset();
	    });
	    
}
sysUserJs.udWizardReset = function(){
	
	$("#w_username").val("");
	$("#w_passward").val("");
	$("#w_passwardAgain").val("");
	$("#w_phone").val("");
	$("#w_email").val("");
	sysUserJs.findAllRoles();
	sysUserJs.wizardModal.reset();
}
sysUserJs.addUser = function(){
	sysUserJs.wizardModal.show();
	sysUserJs.findAllRoles();
	$("#w_roleList").parent().children(".select2-container").css("width","200px");
}
sysUserJs.findAllRoles=function () {	
	var url = "sys/findAllRoles";
	var data = {};
	var successCallBack = function(data) {
		var roleList = $("#w_roleList");
		roleList.html("");
		var htmls = "";
		var rows = data.result;
		for( var index in rows ){
			var tmpRow = rows[index];
			var rowHtml = "<option value='"+tmpRow.roleId+"'>"+tmpRow.roleName+"</option>";
			htmls += rowHtml;
		}
		roleList.html( htmls );
	};

	$.sysAjax(url, data, successCallBack);
}
sysUserJs.createRole=function(){
	var thisWindowId= layer.open({
  	  type: 1,
  	  title: sysi18n.Addrole,
  	  shadeClose: true,
  	  shade: 0,
  	  area: ['800px', '500px'],
  	  btn:[commonI18n.OK , commonI18n.Cancel ],
	  	btn1:function(){ 	//按钮1的回调
	  		sysUserJs.saveRole();
	  		layer.close(thisWindowId);
	  	},
	  	btn2 : function(){
	  layer.close(thisWindowId);
 	},
  	  content:$('#w_addroleDiv')
  	  
	});
}
sysUserJs.opersid=[];
sysUserJs.initAuthTree=function () {
	
	sysShowGlobalLoading();
	var url = "sys/findAllOpers";
	var data = {

	};
	var successCallBack = function(data) {
		var opers = data.result;
		for ( var i in opers) {
			var tmpOper = opers[i];
			aaa = sysi18n[tmpOper.text];
			if( aaa != null ){
				tmpOper.text = aaa;
			}
		}
		treeresult=opers;
		$("#w_authtree").jstree({
			'core' : {
				'data' : treeresult,
			},
			"checkbox" : {
				"keep_selected_style" : false,
//				"tie_selection":false,
//				"three_state":false,
//				"cascade":"up",
			},
			"plugins" : [ "checkbox"],
		}).bind("loaded.jstree", function(e, data) {
			data.instance.open_all();	
			for(var i=0;i<treeresult.length;i++){
				if(data.instance.is_leaf(treeresult[i])){
					data.instance.set_icon(treeresult[i],"glyphicon glyphicon-leaf");
				}
				else{
					data.instance.set_icon(treeresult[i],"glyphicon glyphicon-flash");
				}
			}
		});
		$('#w_authtree').on("changed.jstree", function(e, data) {
			var i, j, r = [],pid,intpid;
			for (i = 0, j = data.selected.length; i < j; i++) {
				var node = data.instance.get_node(data.selected[i]);  
				intpid =parseInt(node.id);;
				var ids = data.instance.get_path(node,"/",true);
				r.push(ids);
			}
			sysUserJs.opersid = r;
		});
	};
	$.sysAjax(url, data, successCallBack);
	
}
sysUserJs.saveRole=function(){
	if($("#w_newRolename").val()!=""){
		sysShowGlobalLoading();
		var url  = "sys/addsysRole";
		var data = {
				rolename:$("#w_newRolename").val(),
				roleremark:$("#w_newRoleremark").val(),
		};
		var successCallBack = function(data) {
			var roleid = data.result[0].roleId;
			var rolename = data.result[0].roleName;
			sysUserJs.findAllRoles();
			sysUserJs.saveOper(roleid,rolename);
		}
		$.sysAjax(url, data, successCallBack);
		}
		else{
			sysShowTip(sysi18n.Null_role);
		}
}
sysUserJs.saveOper=function(roleid,rolename){
	sysShowGlobalLoading();
	var url = "sys/updGrantOperToRole";
	var data = {
		roleId : roleid,
		"opers[]" : sysUserJs.opersid,
		rname:rolename,

	};
	var successCallBack = function(data) {
		if (data.result) {
			sysShowSuccessTip(sysi18n.Save_success);
		} else {
			sysShowTip(sysi18n.Save_failed);
		}
	}
	$.sysAjax(url, data, successCallBack);
	
}
sysUserJs.showAreaByRole=function(){
	var roleList=[];
	$("input[name=belongList]:checked").each(function() {
    		roleList.push($(this).val());
	})
	if(roleList.length>0){
	sysShowGlobalLoading();
		var url = "sys/findsysAreaByRid";
		var data = {
				"rid[]":roleList,
		};
		var successCallBack = function(data) {
			$('#w_areaTree').jstree('uncheck_all');
			var result = data.result;
			var size = result.length;
			for (var i = 0; i < size; i++) {
				var node = $("#w_areaTree").jstree("get_node", data.result[i].id);
//				if ($("#w_areaTree").jstree("is_leaf", data.result[i].id)) {  
	            	$("#w_areaTree").jstree("check_node", data.result[i].id);
//	            }  
				
			}
		
		}
		$.sysAjax(url, data, successCallBack);
	}
	else{
		$('#w_areaTree').jstree('uncheck_all');
	}

	
}
sysUserJs.initAreaTree=function(){
	sysShowGlobalLoading();
	$("#w_areaTree").jstree("destroy");
	var url = "system/area/findsysArea";
	var data = {

	};
	var successCallBack = function(data) {
		$("#w_areaTree").jstree({
			'core' : {
				"check_callback" : true,
				'data' : data.result,
				'multiple':true,
			},
			"checkbox" : {
				"keep_selected_style" : false,
			 "three_state": false,
			},
		
			"plugins" : [ "checkbox" ],
		}).bind("loaded.jstree", function(e, data) {
			data.instance.open_all();
			sysUserJs.showAreaByRole();
		});

	};
	$.sysAjax(url, data, successCallBack);

}
sysUserJs.roleCheckBox=function(){ //角色复选框
	var rolesId = $("#w_roleList").val();
	var rolesName = [];
	$("#w_roleList option").each(function(){
		if($(this).prop("selected"))
			rolesName.push($(this).text());	
	});
	var belongRoleList = $("#belongRoleList");
	belongRoleList.html("");
	var htmls = "<span for='belongList' style='width:50px'>"+sysi18n.role+"</span>&nbsp&nbsp&nbsp"+
	"<span>" +
	"<input type='checkbox' id='checkAllRole' checked>All</span>&nbsp&nbsp&nbsp";
	for( var index in rolesId ){
		var id= rolesId[index];
		var name= rolesName[index];
		var rowHtml = "<span>" +
					"<input type='checkbox' onchange='sysUserJs.showAreaByRole()' name='belongList' id='"+id+"' value='"+id+"' checked>"+name+"</span>&nbsp&nbsp&nbsp";
		htmls += rowHtml;
	}
	belongRoleList.html( htmls );
	$("#checkAllRole").on( "click", function() {
		if ($(this).prop("checked") == true) {
			$("input[name=belongList]").prop("checked",  true );
			sysUserJs.showAreaByRole();
		} else {
			$("input[name=belongList]").prop("checked", false);
			sysUserJs.showAreaByRole();
		}
	});
}
sysUserJs.roleRadio=function(){ //角色单选框
	var rolesId = $("#w_roleList").val();
	var rolesName = [];
	$("#w_roleList option").each(function(){
		if($(this).prop("selected"))
			rolesName.push($(this).text());	
	});
	var belongRoleList = $("#belongRoleList");
	belongRoleList.html("");
	var htmls = "<span for='belongList' style='width:50px'>"+sysi18n.role+"</span>&nbsp&nbsp&nbsp";
	for( var index in rolesId ){
		var id= rolesId[index];
		var name= rolesName[index];
		if(index==0)
			var rowHtml = "<span>" +
			"<input type='radio' onchange='sysUserJs.showAreaByRole()' name='belongList' id='"+name+"' value='"+id+"' checked>"+name+"   </span>&nbsp&nbsp&nbsp";
		else
			var rowHtml = "<span>" +
					"<input type='radio' onchange='sysUserJs.showAreaByRole()' name='belongList' id='"+name+"' value='"+id+"'>"+name+"   </span>&nbsp&nbsp&nbsp";
		htmls += rowHtml;
	}
	belongRoleList.html( htmls );
}
sysUserJs.editAreaTree=function(){
	$("#w_edit").attr("disabled","disabled");
	$("#w_finish").removeAttr("disabled");	
	sysUserJs.roleRadio();
	sysUserJs.showAreaByRole();
}
sysUserJs.finishAreaTree=function(){
	
	var allpid=[];
	var tree = $('#w_areaTree');
	var selects = tree.jstree("get_selected");
	
	for(var index in selects ){
		var pids = tree.jstree("get_path", selects[index], "/", true);
		pids = pids.split("/");
		for(var i in pids){
			if (pids[i] != "-1") {
				allpid.push(pids[i]);
			}
		}
	}
     var dic = {};
     for (var i = allpid.length; i--; ) {//去重
         dic[allpid[i]]=allpid[i];
     }
     var aids = [];
     for (var v in dic) {
    	 aids.push(dic[v]);
     }

	var rids;
	$("input[name='belongList']").each(function() {
		if ($(this).prop("checked")) {
			rids=$(this).val();
		}
	});
	
	sysShowGlobalLoading();
	var url = "sys/editAreasToRoles";
	var data = {
		"aids[]" : aids,
		rids : rids,

	};
	var successCallBack = function(data) {
		if (data.result) {
			if("isAdmin"!=data.result){
				sysShowSuccessTip(sysi18n.Save_success);
			}
			else{
				sysShowTip(sysi18n.isAdmin);
			}
			sysUserJs.roleCheckBox();
			sysUserJs.showAreaByRole();
			$("#w_edit").removeAttr("disabled");
			$("#w_finish").attr("disabled","disabled");
			
		} else {
			sysShowTip(sysi18n.Save_failed);
		}
	};
	$.sysAjax(url, data, successCallBack);
	
	
}
sysUserJs.openAll=function()  {
	$('#w_authtree').jstree('open_all');
}
sysUserJs.closeAll=function () {
	$('#w_authtree').jstree('close_all');
}